package kr.ragne.framework;

import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class SoundManager {
	// 싱글턴 패턴 적용
	private static SoundManager s_instance;
	// 멤버 변수
	private SoundPool mSoundPool;	// 안드로이드에서 지원하는 사운드풀
	private HashMap mSoundPoolMap;	//불러온 사운드의 아이디값을 저장할 해시맵
	private AudioManager mAudioManager;	//사운드를 관리할수 있는 오디오 매니저
	private Context mActivity;	//애플리케이션의 컨텍스트 값
	
	public static SoundManager getInstance(){
		if(s_instance == null){
			s_instance = new SoundManager();
		}
		return s_instance;
	}
	
	private void Init(Context context) {
		//멤버 변수 생성과 초기화
		mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
		mSoundPoolMap = new HashMap<>();
		mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		mActivity = context;
	}
	
	public void addSound(int index, int soundId){
		int id = mSoundPool.load(mActivity, soundId, 1);	//사운드를 로드
		mSoundPoolMap.put(index, id);	//해시맵에 아이디값을 받아온 인덱스로 저장
	}
	
	public void play(int index){
		//사운드 재생
		float streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		streamVolume = streamVolume / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		mSoundPool.play((int) mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
	}
	
	public void playLooped(int index) {
		//사운드 반복 재생
		float streamVolme = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		streamVolme = streamVolme / mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		mSoundPool.play((int) mSoundPoolMap.get(index), streamVolme, streamVolme, 1, -1, 1f);
	}
}
